package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.bean.Employee;
import com.itheima.commons.R;
import com.itheima.exception.CustomException;
import com.itheima.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

/**
 * @author Tang
 * @date 2023/1/6
 */
@Slf4j
@RequestMapping("/employee")
@RestController
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;

    /**
     * 后台员工登录
     * @param employee
     * @return
     */
    @PostMapping("/login")
    public R<Employee> login(@RequestBody Employee employee, HttpSession session){
        //1、将页面提交的密码password进行md5加密处理
        String password = DigestUtils.md5DigestAsHex(employee.getPassword().getBytes());

        //2、根据页面提交的用户名username查询数据库
        LambdaQueryWrapper<Employee> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Employee::getUsername, employee.getUsername());
        Employee emp = employeeService.getOne(lqw);

        //3、如果没有查询到则返回登录失败结果
        if (emp == null) {
            return R.error("该用户不存在！");
        }

        //4、密码比对，如果不一致则返回登录失败结果
        if (!password.equals(emp.getPassword())) {
            return R.error("用户名密码不匹配！");
        }

        //5、查看员工状态，如果为已禁用状态，则返回员工已禁用结果
        if (emp.getStatus() == 0) {
            return R.error("该用户已被禁用！");
        }

        //6、登录成功，将员工id存入Session并返回登录成功结果
        session.setAttribute("employeeId", emp.getId());
        return R.success(emp);
    }

    /**
     * 员工退出
     * @return
     */
    @PostMapping("/logout")
    public R<String> logout(HttpSession session){
        //1.清空session的数据，一次性全部清除
        session.invalidate();

        //2.返回结果
        return R.success("退出成功！");
    }

    /**
     * 新增员工
     * @param employee
     * @return
     */
    @PostMapping
    public R<String> addEmployee(@RequestBody Employee employee, HttpSession session){
        //优化：在新增之前判断一下数据库中是否存在该username
        LambdaQueryWrapper<Employee> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Employee::getUsername, employee.getUsername());
        Employee one = employeeService.getOne(wrapper);
        if (one != null) {
            //return R.error("该用户名已存在！");
            throw new CustomException("该用户名已存在！");
        }

        //1.补齐员工相关字段
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
//        employee.setCreateTime(LocalDateTime.now());
//        employee.setUpdateTime(LocalDateTime.now());
//        Long employeeId = (Long) session.getAttribute("employeeId");
//        employee.setCreateUser(employeeId);
//        employee.setUpdateUser(employeeId);

        //2.调用service的保存方法
        boolean flag = employeeService.save(employee);

        //3.返回结果
        return flag ? R.success("新增员工成功！") : R.error("新增员工失败！");
    }

    /**
     * 员工分页查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page<Employee>> findPage(@RequestParam(defaultValue = "1") Integer page,
                                      @RequestParam(defaultValue = "10") Integer pageSize,
                                      @RequestParam(required = false) String name){
        //0.添加分页拦截器
        //1.获取前端的参数page=1&pageSize=10&name=xxx
        //2.设置查询条件
        LambdaQueryWrapper<Employee> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(name != null, Employee::getName, name);

        //3.创建分页对象
        Page<Employee> employeePage = new Page<>(page, pageSize);

        //4.调用service的分页接口，将分页对象以及查询对象一起传递给分页接口
        employeeService.page(employeePage, wrapper);

        //5.返回结果给前端
        return R.success(employeePage);
    }

    /**
     * 启用|禁用 + 员工编辑
     * @param employee
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody Employee employee, HttpSession session){
        log.info("EmployeeController 线程id: {}",Thread.currentThread().getId());
        //0.更新操作之前，需要补齐字段：更新时间、更新人
//        employee.setUpdateTime(LocalDateTime.now());
//        employee.setUpdateUser((Long) session.getAttribute("employeeId"));

        //优化：编辑员工时，修改用户名为已存在的，会出现问题
        //1.在更新之前做一下用户名判断，根据username查询数据库，排除本身的数据，根据id排除
        if (employee.getUsername() != null) {
            LambdaQueryWrapper<Employee> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Employee::getUsername, employee.getUsername());
            wrapper.ne(Employee::getId, employee.getId());
            int count = employeeService.count(wrapper);
            //2.如果查出来的数据不为空，就代表这个用户名已经存在，直接返回错误结果
            if (count > 0) {
                throw new CustomException("该用户名【"+employee.getUsername()+"】已存在！");
            }
        }

        //3.如果数据为空，可以提交更新操作
        boolean flag = employeeService.updateById(employee);

        //4.返回修改结果
        return flag ? R.success("修改成功！") : R.error("修改失败！");
    }

    /**
     * 根据员工id查询信息
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<Employee> findById(@PathVariable String id){
        //1.调用service的根据id查询接口
        Employee employee = employeeService.getById(id);
        //2.返回查询结果给前端
        return R.success(employee);
    }

}
